package com.zline.foodraise.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mobstat.StatService;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.DetailDynamicAdapter;
import com.zline.foodraise.adapter.PicZoomViewPageAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.CommentBean;
import com.zline.foodraise.entity.CustomerUserBean;
import com.zline.foodraise.entity.MomentBean;
import com.zline.foodraise.entity.PictureBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.listener.DetailDynamicTopListener;
import com.zline.foodraise.listener.PhotoViewListener;
import com.zline.foodraise.listener.RecyclerItemClicked;
import com.zline.foodraise.listener.RecyclerOnScrollListener;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.DrawableDividerItemDecoration;
import com.zline.foodraise.view.MyLinearLayoutManager;
import com.zline.foodraise.view.ViewPagerFixed;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by heshantao on 15/7/15.
 * 动态详情页
 */
@EActivity(R.layout.activity_detail_dynamic)
public class DetailDynamicActivity extends ZlineActivity implements
        RecyclerItemClicked, PhotoViewListener, DetailDynamicTopListener {
    private static final String LOG_TAG = DetailDynamicActivity.class.getSimpleName();
    @StringRes(R.string.detail_dynamic)
    String title;
    @ViewById(R.id.app_common_header_title_tv)
    TextView title_tv;
    @ViewById(R.id.detail_dynamic_comment_recyclerView)
    RecyclerView comment_list_recyclerview;
    @Bean
    DetailDynamicAdapter commentAdapter;
    SparseArray<CommentBean> commentArray;
    @Extra
    MomentBean momentBean;
    //动态列表中的下标
    @Extra
    int position;
    @ViewById(R.id.detaile_dynmaic_fl)
    FrameLayout fl;
    @ViewById(R.id.pics_vp)
    ViewPagerFixed pics_vp;
    @ViewById(R.id.comment_btn)
    Button comment_btn;
    //1代表赞过，0代表未赞过
    int is_support;
    //原始赞的状态
    int originalSupportStatus = -1;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpUtil httpUtil;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    @Bean
    HttpDataParsing httpDataParsing;
    //动态ID
    long momentId;
    //当前页
    int currt_page = 1;
    //共多少页
    int pageCount;
    MyLinearLayoutManager layoutManager;
    //用于添加评论。回复评论，返回刷新数据
    boolean fresh = false;
    @Bean
    PicZoomViewPageAdapter picZoomViewPageAdapter;
    //是否放大图片了
    boolean zoomPic;
    //相对于动态列表赞是否改变
    boolean supportChange = false;
    //相对于动态列表评论是否改变
    boolean commentChange = false;
    //评论列表是否完成初始化
    boolean commentInit = false;
    int commentTotleCount;
    @ViewById(R.id.exception_fl)
    FrameLayout exception_fl;
    @ViewById(R.id.exception_rl)
    RelativeLayout exception_rl;
    @Bean
    NetworkUtil networkUtil;
    //是否加载失败
    boolean loadFail = false;
    //第一次加载数据
    boolean firstLoad = true;
    //加载更多
    boolean loadMore = false;

    @AfterViews
    void doSomeAfterViews() {
        initView();
        if (momentBean != null) {
            originalSupportStatus = momentBean.getIsPraise();
        }
        initData();
    }

    void initView() {
        title_tv.setText(title);
    }

    void initData() {
        if (networkUtil.isNetworkAvailable()) {
            showLoadingDialog();
            showLoadFailView(false);
            requestCommentList();
        } else {
            showLoadFailView(true);
            TUtil.showShort(DetailDynamicActivity.this, R.string.no_network);
        }
    }


    //是否加载失败显示重新加载页面
    void showLoadFailView(boolean isException) {
        loadFail = isException;
        if (isException) {
            exception_fl.setVisibility(View.VISIBLE);
            exception_rl.setVisibility(View.VISIBLE);
        } else {
            exception_fl.setVisibility(View.GONE);
            exception_rl.setVisibility(View.GONE);
        }
    }

    //请求评论列表
    void requestCommentList() {
        momentId = momentBean.getMomentId();
        httpOperator.requestCommentList(httpUtil, Constant.DYNAMIC_TYPE, momentId,
                Constant.PAGE_ROWS_NUMBER, currt_page, requestCommentHandler);
    }


    //获取评论列表回调
    AsyncHttpResponseHandler requestCommentHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestCommentHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        commentArray = httpDataParsing.getCommentList(response);
                        getCommentCount(response);
                        getPageCount(response);
                        if (!fresh) {
                            if (!commentInit) {
                                //初始化
                                setCommentRecyclerView();
                            } else {
                                loadMore(commentArray);
                            }
                        } else {
                            refreshData(commentArray);
                        }

                    } else {
                        loadFailInfo();
                        if (firstLoad) {
                            showLoadFailView(true);
                        } else {
                            httpErro.showCommonErroResult(resultCode);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    dissLoadingDialog();
                    firstLoad = false;
                }
            }

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            dissLoadingDialog();
            loadFailInfo();
            if (firstLoad) {
                showLoadFailView(true);
            }
        }
    };


    //加载更多
    void loadMore(SparseArray<CommentBean> commentArray) {
        loadMore = false;
        if (loadFail) {
            showLoadFailView(false);
        }
        if (currt_page == pageCount) {
            showRecyclerFoot(false);
        }
        commentAdapter.addAll(commentArray);
        changeCommentBtnAndActionBtnStatus(true);
    }

    //添加评论返回后刷新数据
    void refreshData(SparseArray<CommentBean> commentArray) {
        if (loadFail) {
            showLoadFailView(false);
        }
        commentAdapter.setAdapterData(commentArray);
        commentAdapter.notifyDataSetChanged();
        commentChange = true;
        fresh = false;
    }

    //是否显示正在加载
    void showRecyclerFoot(boolean bol) {
        if (commentAdapter != null) {
            commentAdapter.setFootEnable(bol);
            commentAdapter.notifyItemChanged(commentAdapter.getArrys().size() + 1);
        }
    }

    //加载失败时候情况处理
    void loadFailInfo() {
        if (loadMore) {
            currt_page--;
        }
        if (commentAdapter.getFootEnable()) {
            showRecyclerFoot(false);
        }
        firstLoad = false;
        fresh = false;
    }


    //评论分页查找共多少页
    @Background
    void getPageCount(JSONObject json) {
        try {
            JSONObject jsonObject = json.getJSONObject(Constant.COMMENT_BEAN_PAGE);
            pageCount = jsonObject.getInt(Constant.PAGE_COUNT);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    //评论共有多少条评论
    @Background
    void getCommentCount(JSONObject json) {
        try {
            JSONObject jsonObject = json.getJSONObject(Constant.COMMENT_BEAN_PAGE);
            commentTotleCount = jsonObject.getInt(Constant.FULL_LIST_SIZE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    void setCommentRecyclerView() {
        comment_list_recyclerview.addItemDecoration(new DrawableDividerItemDecoration(getResources().getDrawable(R.drawable.recycleview_divider), false, false));
        comment_list_recyclerview.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);//去除阴影
        comment_list_recyclerview.setItemAnimator(new DefaultItemAnimator());
        layoutManager = new MyLinearLayoutManager(DetailDynamicActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        comment_list_recyclerview.setLayoutManager(layoutManager);
        commentAdapter.setAdapterData(commentArray);
        commentAdapter.setHeaderData(momentBean);
        commentAdapter.setRecycleItemClickListener(this);
        commentAdapter.setDetailDynamicTopListener(this);
        comment_list_recyclerview.setAdapter(commentAdapter);
        comment_list_recyclerview.addOnScrollListener(new RecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore() {
                if (currt_page < pageCount) {
                    if (networkUtil.isNetworkAvailable()) {
                        currt_page++;
                        loadMore = true;
                        showRecyclerFoot(true);
                        requestCommentList();
                    } else {
                        TUtil.showShort(DetailDynamicActivity.this, R.string.fail_load_data);
                    }
                }
            }
        });
        commentInit = true;
        changeCommentBtnAndActionBtnStatus(true);
    }


    @OnActivityResult(Constant.DYNAMIC_REQUEST_CODE)
    void onActivityResult() {
        currt_page = 1;
        fresh = true;
        if (networkUtil.isNetworkAvailable()) {
            requestCommentList();
        } else {
            TUtil.showShort(DetailDynamicActivity.this, R.string.fail_load_data);
        }
    }


    @Click({R.id.app_common_header_left_icon_iv
            , R.id.comment_btn, R.id.reload_tv
    })
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.comment_btn:
                momentId = momentBean.getMomentId();
                ReleaseCommentActvity_.intent(this)
                        .flag(Constant.ADD_COMMENT_FLAG).resourceType(Constant.DYNAMIC_TYPE)
                        .resourceId(momentId).startForResult(Constant.DYNAMIC_REQUEST_CODE);
                break;
            case R.id.reload_tv:
                initData();
                break;
            default:
                break;
        }
    }


    void setResult() {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putBoolean(Constant.SUPPORT_CHANGE, supportChange);
        bundle.putBoolean(Constant.COMMENT_CHANGE, commentChange);
        bundle.putInt(Constant.POSITION, position);
        bundle.putInt(Constant.SUPPORT_STATUS, is_support);
        bundle.putInt(Constant.TOTLE_COMMENT_COUNT, commentTotleCount);
        Parcelable[] comments = commentList2Parcelables(commentArray);
        bundle.putParcelableArray(Constant.DYNAMIC_COMMENT_LIST, comments);
        intent.putExtras(bundle);
        setResult(Constant.DETAIL_DYNAMCI_REQUEST_CODE, intent);
    }


    //将评论列表转化为parcelable 数组
    Parcelable[] commentList2Parcelables(SparseArray<CommentBean> array) {
        if (array == null) {
            return null;
        }
        Parcelable[] parcels = new Parcelable[array.size()];
        for (int i = 0; i < array.size(); i++) {
            parcels[i] = array.get(i);
        }
        return parcels;
    }

    //改变评论，float评论可见情况
    void changeCommentBtnAndActionBtnStatus(boolean bol) {
        if (bol) {
            comment_btn.setVisibility(View.VISIBLE);
        } else {
            comment_btn.setVisibility(View.GONE);
        }

    }


    @Override
    public void goback() {
        setResult();
        finish();
    }

    @Override
    public void onBackPressed() {
        if (zoomPic) {
            onViewTap();
        } else {
            goback();
        }
    }


    //点击放大图片
    void showZoomPics(int position) {
        if (momentBean == null) return;
        zoomPic = true;
        List<PictureBean> list = momentBean.getPictureBeanList();
        picZoomViewPageAdapter.setPicList(list);
        picZoomViewPageAdapter.setPhotoViewListener(this);
        pics_vp.setAdapter(picZoomViewPageAdapter);
        pics_vp.setCurrentItem(position);
        fl.setVisibility(View.VISIBLE);
        changeCommentBtnAndActionBtnStatus(false);
    }

    //点击放大图片
    void showZoomPics(int position, int parentPosition) {
        CommentBean commentBean = null;
        commentBean = commentAdapter.getArrys().get(parentPosition - 1);
        if (commentBean == null) return;
        zoomPic = true;
        List<PictureBean> list = commentBean.getPictureBeanList();
        picZoomViewPageAdapter.setPicList(list);
        picZoomViewPageAdapter.setPhotoViewListener(this);
        pics_vp.setAdapter(picZoomViewPageAdapter);
        pics_vp.setCurrentItem(position);
        fl.setVisibility(View.VISIBLE);
        changeCommentBtnAndActionBtnStatus(false);
    }


    @Override
    public void onRecyclerItemClicked(int position) {

    }

    @Override
    public void onRecyclerItemClicked(int flag, int position) {
        switch (flag) {
            case Constant.DYNAMIC_PICT_FLAG:
                LUtil.i(LOG_TAG, "_____动态详情__________");
                showZoomPics(position);
                break;
            case Constant.DYNAMIC_SUPPORT_FLAG:
                if (momentBean != null) {
                    momentId = momentBean.getMomentId();
                    SupportListActivity_.intent(this).momentId(momentId).start();
                }
                break;
            case Constant.DYNAMIC_COMMENT_FLAG:
                CommentBean commentBean = commentAdapter.getArrys().get(position - 1);
                momentId = momentBean.getMomentId();
                if (commentBean == null) return;
                ReleaseCommentActvity_.intent(this)
                        .flag(Constant.REPLY_COMMENT_FLAG).resourceType(Constant.DYNAMIC_TYPE)
                        .resourceId(momentId).commentBean(commentBean)
                        .startForResult(Constant.DYNAMIC_REQUEST_CODE);
                break;
            case Constant.DYNAMIC_THIRD_PERSONAL_FLAG:
                if (momentBean != null) {
                    CommentBean mCommentBean = commentAdapter.getArrys().get(position - 1);
                    if (mCommentBean != null) {
                        CustomerUserBean customerUserBean = mCommentBean.getUserBean();
                        long userId = customerUserBean.getUserId();
                        PersonalHomePageActivity_.intent(this).userId(userId).start();
                    }

                }
                break;
            default:
                break;
        }

    }

    @Override
    public void onRecyclerItemClicked(int flag, int position, int parent) {
        if (flag == Constant.DETAIL_DYNAMIC_COMMENT_LIST_PICS_FLAG) {
            showZoomPics(position, parent);
        }

    }

    @Override
    public void onRecyclerClickedDelete(int position) {

    }

    @Override
    public void onViewTap() {
        zoomPic = false;
        fl.setVisibility(View.GONE);
        changeCommentBtnAndActionBtnStatus(true);
    }

    @Override
    public void changeSupport(int support_status) {
        if (originalSupportStatus == support_status) {
            supportChange = false;
        } else {
            supportChange = true;
        }
        is_support = support_status;
    }

    @Override
    public void openOneDynamicPic() {
        showZoomPics(0);
    }

    @Override
    public void onResume() {
        super.onResume();
        StatService.onResume(this);
        StatService.onPageStart(this, Constant.DETAIL_DYNAMIC);
    }

    @Override
    public void onPause() {
        super.onPause();
        StatService.onPause(this);
        StatService.onPageEnd(this, Constant.DETAIL_DYNAMIC);

    }
}
